package com.farm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.farm.common.BaseContext;
import com.farm.common.States;
import com.farm.filter.SusceptibleFilter;
import com.farm.mapper.AnswerMapper;
import com.farm.mapper.LoveMapper;
import com.farm.pojo.Answer;
import com.farm.pojo.Commited;
import com.farm.mapper.CommitMapper;
import com.farm.pojo.DTO.InquiryDto;
import com.farm.pojo.Vo.CollectedVo;
import com.farm.pojo.Vo.QuestionVo;
import com.farm.pojo.Vo.ReplyVo;
import com.farm.pojo.love;
import com.farm.service.CommitService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kennycason.kumo.WordFrequency;
import com.kennycason.kumo.nlp.FrequencyAnalyzer;
import com.kennycason.kumo.nlp.tokenizers.ChineseWordTokenizer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 发布文章 服务实现类
 * </p>
 *
 * @author farm
 * @since 2023-10-30
 */
@Service
@Slf4j
public class CommitServiceImpl extends ServiceImpl<CommitMapper, Commited> implements CommitService {

    @Autowired
    private CommitMapper commitMapper;
    @Autowired
    private AnswerMapper answerMapper;
    @Autowired
    private LoveMapper loveMapper;

    @Autowired
    private SusceptibleFilter susceptibleFilter;


    /**
     * 发布问答
     * @param questionVo
     */
    @Override
    public void postQuestion(QuestionVo questionVo) {
        if (questionVo.getContent().equals("")){
            return;
        }
        // 获取图片列表数据
        List<Object> imageList = questionVo.getPicList();
        List<String> imageNameList = new ArrayList<>();
        for(Object image : imageList){
            Class imageClass = image.getClass();
            try {
                // 获取其字段
                Field fieldName = imageClass.getDeclaredField("head");
                fieldName.setAccessible(true);
                // 获取其属性值
                Object value = fieldName.get(image);
                String name = value.toString().substring(5);
                System.out.println(name);
                imageNameList.add(name);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer();
        // 设置分词返回数量(频率最高的600个词)
        frequencyAnalyzer.setWordFrequenciesToReturn(600);
        // 最小分词长度
        frequencyAnalyzer.setMinWordLength(2);
        // 引入中文解析器
        frequencyAnalyzer.setWordTokenizer(new ChineseWordTokenizer());
        List<String> list = new ArrayList<>();
        list.add(questionVo.getContent());
        final List<WordFrequency> wordFrequencies = frequencyAnalyzer.load(list);
        int size = wordFrequencies.size();
        StringBuilder stringBuilder = new StringBuilder();
        if(size < 3 && size > 0){
            for(int i = 0;i<size;i++){
                stringBuilder.append(wordFrequencies.get(i).getWord());
                stringBuilder.append(',');
            }
        }else if(size == 0){
            stringBuilder.append("");
        }else {
            for(int i = 0;i<3;i++){
                stringBuilder.append(wordFrequencies.get(i).getWord());
                stringBuilder.append(',');
            }
        }
        String label  = stringBuilder.toString();
        Commited commit = Commited.builder()
                .userId(BaseContext.getCurrentId())
                .content(susceptibleFilter.WordFilter(questionVo.getContent()))
                // 将数组转换为字符串
                .picList(String.join(",", imageNameList))
                .partitions(Long.valueOf(questionVo.getPartitions()))
                .label(label)
                .build();
        commitMapper.insert(commit);
    }

    /**
     * 显示查询数据
     * @param commitedList
     * @return
     */
    private List<InquiryDto> Inquiry(List<Commited> commitedList){
        // 查询当前用户点赞内容
        Long CurrentUserId = BaseContext.getCurrentId();
        QueryWrapper<love> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("commit_id as commitId, liking, disliking, collection");
        queryWrapper.lambda().eq(love::getUserId, CurrentUserId).isNotNull(love::getCommitId).orderByAsc(love::getCommitId);
        List<Map<String, Object>> mapList = loveMapper.selectMaps(queryWrapper);

        // 定义mapList下标
        Integer indexList = 0;
        boolean flag = true;
        if(mapList.size() == 0){
            flag = false;
        }

        List<InquiryDto> inquiryDtoList = new ArrayList<>();
        for (Commited commited : commitedList){

            // 封装返回值InquiryDto
            InquiryDto inquiryDto = InquiryDto.builder().commitId(commited.getCommitId())
                    .userId(commited.getUserId())
                    .content(commited.getContent())
                    .liking(commited.getLiking())
                    .collection(commited.getCollection())
                    .likeState(States.DISABLE)
                    .dislikeState(States.DISABLE)
                    .collectionState(States.DISABLE)
                    .build();
            // 保持查询结果的健壮性
            if (flag){
                while(true){
                    if(commited.getCommitId().compareTo((Long)mapList.get(indexList).get("commitId")) < 0){
                        break;
                    }else if(commited.getCommitId().equals(mapList.get(indexList).get("commitId"))){
                        // 点赞结果判断
                        if(mapList.get(indexList).get("liking") == States.ENABLE)
                        {
                            inquiryDto.setLikeState(States.ENABLE);
                            System.out.println("我这里点赞了："+ commited.getCommitId());
                        }else {
                            System.out.println("我进来了哈哈哈");
                            if(mapList.get(indexList).get("disliking") == States.ENABLE)
                            {
                                inquiryDto.setDislikeState(States.ENABLE);
                                System.out.println("这里点了差评：" + commited.getCommitId());
                            }
                        }


                        // 收藏结果判断
                        if(mapList.get(indexList).get("collection") == States.ENABLE){
                            inquiryDto.setCollectionState(States.ENABLE);
                        }
                        indexList++;
                        if(mapList.size() <= indexList ){
                            indexList = 0;
                            flag = false;
                        }
                        break;
                    }else {
                        indexList++;
                        if(mapList.size() <= indexList ){
                            indexList = 0;
                            flag = false;
                            break;
                        }
                    }

                }

            }
            // 将图片路径封装为数组
            List<String> picList = Arrays.asList(commited.getPicList().split(","));
            inquiryDto.setPicList(picList);

            // 查询评论的内容
            Long commitId = commited.getCommitId();
            QueryWrapper<Answer> qw = new QueryWrapper<>();
            qw.select("user_id as userAnswerId", "respond");
            qw.lambda().eq(Answer::getCommitId, commitId).eq(Answer::getState, States.ENABLE);
            List<Map<String, Object>> answerList = answerMapper.selectMaps(qw);
            if (answerList != null && answerList.size() > 0){
                inquiryDto.setAnswerList(answerList);
            }
            inquiryDtoList.add(inquiryDto);
            log.info(String.valueOf(inquiryDto));
        }
        return inquiryDtoList;
    }



    /**
     * 查看问答详情
     *
     * @return
     */
    @Override
    @Transactional
    public List<InquiryDto> showInquiry(String partitions) {
        LambdaQueryWrapper<Commited> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Commited::getState, States.ENABLE);
        if (partitions != null && !partitions.equals("")){
            lqw.eq(Commited::getPartitions, Long.valueOf(partitions));
        }
        List<Commited> commitedList = commitMapper.selectList(lqw);
        if (commitedList == null || commitedList.size() == 0){
            return null;
        }
        List<InquiryDto> inquirys = Inquiry(commitedList);
        return inquirys;
    }

    /**
     * 添加回复
     * @param replyVo
     */
    @Override
    public void addReply(ReplyVo replyVo) {
        Answer answerReply = new Answer();
        BeanUtils.copyProperties(replyVo, answerReply);
        answerReply.setUserId(BaseContext.getCurrentId());
        log.info(answerReply.toString());
        answerMapper.insert(answerReply);
    }

    /**
     * 点赞
     * @param commitId
     * @param liking
     */
    @Transactional
    @Override
    public void addLove(Long commitId, Integer liking) {
        // 查询评论表更新评论数据
//        LambdaQueryWrapper<Commited> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Commited::getCommitId, commitId);
        Commited commited = commitMapper.selectById(commitId);
        // 如果是0则是取消点赞
        if(liking.equals(States.DISABLE)){
            commited.setLiking(commited.getLiking() - 1);
        }else if (liking.equals(States.ENABLE)){
            // 如果是1则是点赞
            commited.setLiking(commited.getLiking() + 1);
        }
        // 插入数据
        commitMapper.updateById(commited);
        System.out.println("操作了外层表");

        LambdaQueryWrapper<love> lqw = new LambdaQueryWrapper<>();
        lqw.eq(love::getCommitId, commitId).eq(love::getUserId, BaseContext.getCurrentId());
        List<love> loves = loveMapper.selectList(lqw);

        if (loves.size() == 0){
            // 如果不存在则直接构造插入
            love loveNew = love.builder()
                    .userId(BaseContext.getCurrentId())
                    .commitId(commitId)
                    .liking(liking)
                    .build();
            loveMapper.insert(loveNew);
            System.out.println("操作了插入表");
        }else{
            love loveOne = loves.get(0);
            loveOne.setLiking(liking);
            loveMapper.updateById(loveOne);
//            int i = loveMapper.deleteById(loveOne.getId());
//            System.out.println(i);
//            loveOne.setLiking(liking);
//            loveMapper.insert(loveOne);

        }



    }

    /**
     * 收藏的实现
     * @param collectedVo
     */
    @Override
    @Transactional
    public void collected(CollectedVo collectedVo) {
        Commited commited = commitMapper.selectById(collectedVo.getCommitId());
        // 如果是0则是取消收藏
        if(collectedVo.getCollection().equals(States.DISABLE)){
            commited.setCollection(commited.getCollection() - 1);
        }else if (collectedVo.getCollection().equals(States.ENABLE)){
            // 如果是1则是收藏
            commited.setCollection(commited.getCollection() + 1);
        }
        // 插入数据
        commitMapper.updateById(commited);

        LambdaQueryWrapper<love> lqw = new LambdaQueryWrapper<>();
        lqw.eq(love::getCommitId, collectedVo.getCommitId()).eq(love::getUserId, BaseContext.getCurrentId());
        List<love> loves = loveMapper.selectList(lqw);
        if (loves.size() == 0){
            // 如果不存在则直接构造插入
            love loveNew = love.builder()
                    .userId(BaseContext.getCurrentId())
                    .commitId(collectedVo.getCommitId())
                    .collection(collectedVo.getCollection())
                    .build();
            loveMapper.insert(loveNew);
        }else{
            // 如果存在则先删除后插入
            love loveOne = loves.get(0);
            loveOne.setCollection(collectedVo.getCollection());
            loveMapper.updateById(loveOne);
//            loveMapper.deleteById(loveOne.getId());
//            loveOne.setCollection(collectedVo.getCollection());
//            loveMapper.insert(loveOne);
        }
    }

    /**
     * 查询我的发布
     * @return
     */
    @Override
    public List<InquiryDto> MyInquiry() {
        LambdaQueryWrapper<Commited> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Commited::getUserId, BaseContext.getCurrentId())
                .eq(Commited::getState, States.ENABLE)
                .orderByAsc(Commited::getCommitId);
        List<Commited> commiteds = commitMapper.selectList(lqw);
        log.info("我的发布："+ commiteds);
        List<InquiryDto> inquiryDtoList = Inquiry(commiteds);
        return inquiryDtoList;
    }

    /**
     * 删除问答
     * @param commitId
     */
    @Override
    @Transactional
    public void deleteByCommitId(Long commitId) {
//        删除commited表
        commitMapper.deleteById(commitId);
        // 删除love表
        LambdaQueryWrapper<love> lqw = new LambdaQueryWrapper<>();
        lqw.eq(love::getCommitId, commitId);
        loveMapper.delete(lqw);
        LambdaQueryWrapper<Answer> lqwAnswer = new LambdaQueryWrapper<>();
        lqwAnswer.eq(Answer::getCommitId, commitId);
        answerMapper.delete(lqwAnswer);
    }

    /**
     * 不喜欢
     * @param commitId
     * @param dislike
     */
    @Override
    public void disliked(Long commitId, Integer dislike) {

        LambdaQueryWrapper<love> lqw = new LambdaQueryWrapper<>();
        lqw.eq(love::getCommitId, commitId).eq(love::getUserId, BaseContext.getCurrentId());
        System.out.println("用户id: " + BaseContext.getCurrentId() );
        List<love> loves = loveMapper.selectList(lqw);
        System.out.println("不喜欢状态：" + dislike);
        if (loves.size() == 0) {
            // 如果不存在则直接构造插入
            love loveNew = love.builder()
                    .userId(BaseContext.getCurrentId())
                    .commitId(commitId)
                    .disliking(dislike)
                    .build();
            loveMapper.insert(loveNew);
        } else {
            love loveOne = loves.get(0);
            loveOne.setDisliking(dislike);
            // 判断点赞与不喜欢
            if (dislike.equals(States.ENABLE)) {
                if (loveOne.getLiking().equals(States.ENABLE)) {
                    loveOne.setLiking(States.DISABLE);
                    Commited commited = commitMapper.selectById(commitId);
                    commited.setLiking(commited.getLiking() - 1);
                    commitMapper.updateById(commited);
                }
            }
            loveMapper.updateById(loveOne);
        }
    }



    /**
     * 我的收藏
     * @return
     */
    @Override
    public List<InquiryDto> MyCollection() {
        LambdaQueryWrapper<love> lqw = new LambdaQueryWrapper<>();
        lqw.eq(love::getUserId, BaseContext.getCurrentId())
                .eq(love::getCollection, States.ENABLE).orderByAsc(love::getCommitId);
        List<love> loves = loveMapper.selectList(lqw);
        if (loves == null || loves.size() == 0 ){
            return null;
        }
        // 查询状态
        LambdaQueryWrapper<Commited> lqwCommited = new LambdaQueryWrapper<>();
        lqwCommited.eq(Commited::getState, States.ENABLE);
        List<Commited> commiteds = commitMapper.selectList(lqwCommited);
        if (commiteds == null || commiteds.size() == 0 ){
            return null;
        }

        List<Commited> commitIdList = new ArrayList<>();
        int i = 0, j = 0;
        while (i < commiteds.size() && j < loves.size()){
            if (commiteds.get(i).getCommitId().equals(loves.get(j).getCommitId())){
                commitIdList.add(commiteds.get(i));
                i++;
                j++;
            }else if(commiteds.get(i).getCommitId().compareTo(loves.get(j).getCommitId()) > 0){
                j++;
            }
            else {
                i++;
            }
        }

//        List<Commited> commiteds = commitMapper.selectBatchIds(commitIdList);

        List<InquiryDto> inquiryDtoList = Inquiry(commitIdList);
        return inquiryDtoList;
    }


}
